import {
  getNoitceListAPi,
  createNoticeApi,
  updateNoticeApi,
  deleteNoticeApi,
  getNoticeListByNoticeTitleApi,
} from "@/api/notice";
import { ref } from "vue";
import { defineStore } from "pinia";
import { ElMessage } from "element-plus";

export const useNoticeStore = defineStore(
  "notice",
  () => {
    const noticeList = ref([]);

    async function getNoticeList(currentPage, pageSize) {
      const res = await getNoitceListAPi(currentPage, pageSize);
      if (res.data.code === 200) {
        noticeList.value = res.data.data;
        return true;
      } else {
        ElMessage.error({
          message: res.data.msg,
        });
        console.log("获取公告失败");
      }
    }

    async function createNotice(data) {
      const res = await createNoticeApi(data);
      if (res.data.code === 200) {
        return true;
      } else {
        ElMessage.error({
          message: res.data.msg,
        });
        console.log("创建公告失败");
        return false;
      }
    }

    async function updateNotice(data) {
      const res = await updateNoticeApi(data);
      if (res.data.code === 200) {
        return true;
      } else {
        ElMessage.error({
          message: res.data.msg,
        });
        console.log("更新公告失败");
        return false;
      }
    }

    async function deleteNotice(id) {
      const res = await deleteNoticeApi(id);
      if (res.data.code === 200) {
        return true;
      } else {
        ElMessage.error({
          message: res.data.msg,
        });
        console.log("删除公告失败");
        return false;
      }
    }

    async function getNoticeListByNoticeTitle(
      noticeTitle,
      currentPage,
      pageSize
    ) {
      console.log(noticeTitle);
      const res = await getNoticeListByNoticeTitleApi(
        noticeTitle,
        currentPage,
        pageSize
      );
      console.log(res);
      if (res.data.code === 200) {
        noticeList.value = res.data.data;
        return true;
      } else {
        ElMessage.error({
          message: res.data.msg,
        });
      }
    }

    return {
      noticeList,
      getNoticeList,
      createNotice,
      updateNotice,
      deleteNotice,
      getNoticeListByNoticeTitle,
    };
  },
  {
    persist: {
      storage: sessionStorage,
      paths: ["noticeList"],
    },
  }
);

export const useNoticeStoreHook = () => {
  return useNoticeStore();
};
